import Icon from '../../../components/icon'
import Input from '@/components/Input'
import NavBar from '../../../components/NavBar'
import { memo, useEffect, useRef, useState } from 'react'
import { useSelector } from 'react-redux'
import styles from './index.module.scss'
import io from 'socket.io-client'
import { getItem } from '@/utils/storage'
import { useDispatch } from 'react-redux'
import { getUser } from '../store/action'

const Chat = () => {
  const clientRef = useRef('')
  const dispatch = useDispatch()
  const listRef = useRef()

  useEffect(() => {
    dispatch(getUser())
    const client = io('http://geek.itheima.net', {
      query: {
        token: getItem().token,
      },
      transports: ['websocket'],
    })
    client.on('connect', function () {
      setMessageList([
        ...messageList,
        { type: 'robot', text: '你好啊！我们现在可以聊天了!' },
      ])
    })
    clientRef.current = client
    return () => {
      client.close()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const [messageList, setMessageList] = useState([
    // 放两条初始消息
    { type: 'robot', text: '亲爱的用户您好，小智同学为您服务。' },
    { type: 'user', text: '你好' },
  ])

  const [msg, setMsg] = useState('')

  useEffect(() => {
    listRef.current.scrollTop = listRef.current.scrollHeight
    clientRef.current.on('message', (text) => {
      setMessageList([...messageList, { type: 'robot', text: text.msg }])
    })
  }, [messageList, msg])

  const onkeyup = (e) => {
    if (msg === '') return
    if (e.keyCode === 13) {
      setMessageList([...messageList, { type: 'user', text: msg }])
      clientRef.current.emit('message', {
        msg,
        timestamp: new Date(),
      })
      setMsg('')
    }
    return
  }
  const user = useSelector((state) => state.userReducer.user)

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar className="fixed-header">小智同学</NavBar>

      {/* 聊天记录列表 */}
      <div className="chat-list" ref={listRef}>
        {messageList.map((i, index) =>
          i.type === 'robot' ? (
            <div className="chat-item" key={index}>
              <Icon type="iconbtn_xiaozhitongxue" />
              <div className="message">{i.text}</div>
            </div>
          ) : (
            <div className="chat-item user" key={index}>
              <img
                src={
                  user.photo ||
                  'http://toutiao.itheima.net/images/user_head.jpg'
                }
                alt=""
              />
              <div className="message">{i.text}</div>
            </div>
          )
        )}
      </div>

      {/* 底部消息输入框 */}
      <div className="input-footer">
        <Input
          className="no-border"
          placeholder="请描述您的问题"
          value={msg}
          onChange={(e) => {
            if (e.target.value.trim() === '') {
              return
            } else {
              return setMsg(e.target.value)
            }
          }}
          onKeyUp={onkeyup}
        />
        <Icon type="iconbianji" />
      </div>
    </div>
  )
}

export default memo(Chat)
